package com.edu.whu.service.impl;

import com.edu.whu.dao.TokenUserRepository;
import com.edu.whu.dao.UserInfoJpaRepository;
import com.edu.whu.entity.TokenUser;
import com.edu.whu.entity.UserInfo;
import com.edu.whu.service.ServiceException;
import com.edu.whu.service.TokenUserService;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class TokenUserImpl implements TokenUserService {
    private final UserInfoJpaRepository userInfoJpaRepository;
    private final TokenUserRepository tokenUserRepository;

    public TokenUserImpl(TokenUserRepository tokenUserRepository, UserInfoJpaRepository userInfoJpaRepository) {
        this.tokenUserRepository = tokenUserRepository;
        this.userInfoJpaRepository = userInfoJpaRepository;
    }

    @Override
    public String acquireToken(String userAccount) {
        String token = UUID.randomUUID().toString();
        tokenUserRepository.save(new TokenUser(token, userAccount));
        return token;
    }

    @Override
    public UserInfo checkToken(String token) throws ServiceException {
        TokenUser tokenUser = tokenUserRepository.findById(token).orElse(null);
        if (tokenUser == null) {
            throw new ServiceException("无效token");
        }
        UserInfo userInfo = userInfoJpaRepository.findById(tokenUser.getUserId()).orElse(null);
        if (userInfo == null) {
            throw new ServiceException("无效token");
        }
        return userInfo;
    }
}
